package com.yuntsg.ruiijn.controller.admin;


import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuntsg.nnsfcp.common.utils.UserUtil;
import com.yuntsg.ruiijn.controller.system.InitController;
import com.yuntsg.ruiijn.database.entity.*;
import com.yuntsg.ruiijn.database.mapper.*;
import com.yuntsg.ruiijn.databse_search.mapper.FileDetailsMapper;
import com.yuntsg.ruiijn.databse_search.mapper.FileRecordsMapper;
import com.yuntsg.ruiijn.databse_search.service.FileDetailService;
import com.yuntsg.ruiijn.databse_search.service.FileRecordsService;
import com.yuntsg.ruiijn.entity.AuthorMess;
import com.yuntsg.ruiijn.entity.CoAuthor;
import com.yuntsg.ruiijn.entity.KeyAndValue;
import com.yuntsg.ruiijn.entity.RpAuthor;
import com.yuntsg.ruiijn.paperana.controller.SearchController;
import com.yuntsg.ruiijn.service.AsyncService;
import com.yuntsg.ruiijn.service.UploadCnService;
import common.aopLog.OperationLog;
import com.yuntsg.nnsfcp.common.beans.ResultBean;
import common.util.*;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import static com.yuntsg.ruiijn.JiaXinZhi.InfoGetRuleName.getRuleName;


@RestController
@RequestMapping("unit_basic")
@Slf4j
@SuppressWarnings("ALL")
//@Api(tags = "单位下文章的具体操作")
public class WosBasicController {


    @Value("${upload.path}")
    public String uploadPath;

    @Resource
    UserUtil userUtil;

    @Value("${upload.resultPath}")
    public String resultPath;

    @Value("${unit.onTrial}")
    public Integer onTrial;
    @Resource
    RuijinSameConfigMapper ruijinSameConfigMapper;
    @Autowired
    private FileRecordsService fileRecordsService;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private UnitDeptMapper unitDeptMapper;
    @Autowired
    private UnitBasicMapper unitBasicMapper;
    @Autowired
    private WosBasicMapper wosBasicMapper;
    @Autowired
    private WosExtendMapper wosExtendMapper;
    @Autowired
    private HttpSession session;
    @Autowired
    private InitController initController;
    @Autowired
    private FileDetailService fileDetailService;
    @Autowired
    private FileRecordsMapper fileRecordsMapper;
    @Autowired
    private FileDetailsMapper fileDetailsMapper;
    @Autowired
    private MinioUtil minioUtil;
    @Autowired
    private SearchController searchController;
    @Autowired
    private PaperAnaMapper anaMapper;
    @Autowired
    private AsyncService asyncService;
    @Autowired
    private SysQueenMapper sysQueenMapper;
    @Autowired
    private UploadCnService uploadCnService;

    public static String getC1(String c1) {
        try {
            c1 = (c1.startsWith("[") && c1.contains("]")) ? c1.substring(c1.indexOf("]") + 1).trim() : c1;
            c1 = (c1.contains("[")) ? c1.substring(0, c1.indexOf("[")) : c1;
        } catch (Exception e) {
            System.out.println("获取C1失败___");
        }
        return c1;
    }

    public static String getC1Msg(String c1) {
        try {
            c1 = (c1.startsWith("[") && c1.contains("]")) ? c1.substring(c1.indexOf("]") + 1).trim() : c1;
        } catch (Exception e) {
            System.out.println("获取C1信息失败___");
        }

        return c1;
    }

    public static boolean affiliated(String c1OrRp) {
        String s = c1OrRp.toLowerCase();
        return !s.contains(" 252hosp") && !s.contains(" 302hosp") && !s.contains(" 401hosp") && !s.contains(" chinahosp") && !s.contains(" genhosp") && !s.contains(" hosp ") && !s.contains(" hosp,") && !s.contains(" hosp.") && !s.contains(" hosp1,") &&
                !s.contains(" hosp1.") && !s.contains(" hosphosp") && !s.contains(" hospital") && !s.contains(" hospita") && !s.contains(" hospitial") && !s.contains(" hospitol") && !s.contains(" hosptal") && !s.contains(" hosptial") &&
                !s.contains(" hosptital") && !s.contains(", hosp ") && !s.contains(",hosp ") && !s.contains("101hosp") && !s.contains("301hosp") && !s.contains("affiliated ") && !s.contains("affiliatedhosp") && !s.contains("centralhosp") &&
                !s.contains("childrenshosp") && !s.contains("gastrointestinalhosp") && !s.contains("peoples hosp") && !s.contains("qiluhosp") && !s.contains("ren jihosp") && !s.contains("tongjihosp") && !s.contains("xuanwuhosp") && !s.contains("zhongshanhosp");
    }

    //    //@ApiOperation(value = "更新所有数据")
    @GetMapping("upload_data")
    public void upload_data() throws Exception {
        initController.run();
    }

    //    //@ApiOperation(value = "上传中文数据")
    @GetMapping("upload_cn")
    public void upload_cn(String path, Integer gid, Integer type) {
        path = uploadPath + path;
        String searchPlan = unitBasicMapper.selectById(gid).getSearchPlan();
        if (type == 5) {
            uploadCnService.cnki(path, searchPlan, gid);
        } else if (type == 6) {
            uploadCnService.wf(path, searchPlan, gid);
        } else if (type == 7) {
            uploadCnService.cqvip(path, searchPlan, gid);
        } else if (type == 4) {
            uploadCnService.pubmed(path, searchPlan, gid);
        }
    }

    //    //@ApiOperation(value = "01-上传WOS文件")
    @GetMapping("upload_excel")
    public ResultBean<Object> upload_excel(String path, Integer gid) {
        UnitBasic unitBasic = unitBasicMapper.selectById(gid);
        //各个路径
        String[] split = path.split("###");
        int count = 0;
        // 通过前后端约定的参数名获取参数，这里是json字符串
        try {
            for (String pathOneFile : split) {
                Integer integer = start(pathOneFile, unitBasic.getSearchPlan(), gid);
                System.out.println("入库成功的条数是___" + integer);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultBean<>(-99, "操作失败,请上传指定格式文件");
        }
        Long countWos = new LambdaQueryChainWrapper<>(wosBasicMapper).eq(WosBasic::getSoType, 1).eq(WosBasic::getGid, unitBasic.getId()).count();
        unitBasic.setSearchNum("" + countWos);
        unitBasic.setSysUpdateTime(LocalDateTime.now());
        unitBasicMapper.updateById(unitBasic);
        return new ResultBean<>("操作成功");
    }

    //    //@ApiOperation(value = "06-本地文献模块,修改信息")
    @GetMapping("upload_pdf_local_change")
//    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "当前文章ID"), @ApiImplicitParam(name = "deptId", value = "科室ID,当前文章在哪个科室下"), @ApiImplicitParam(name = "path", value = "先调用上传接口 上传接口返回文件路径后当做参数带回到这里"), @ApiImplicitParam(name = "title", value = "文章标题"), @ApiImplicitParam(name = "belongDate", value = "归属日期"), @ApiImplicitParam(name = "author", value = "归属日期"),})
    public ResultBean<Object> upload_pdf_local_change(String author, String belongDate, String id, String
            path, String title, Integer deptId) {
        UnitDept unitDept = unitDeptMapper.selectById(deptId);

        WosBasic wosBasic = wosBasicMapper.selectById(id);
        wosBasic.setSysCreateTime(LocalDateTime.now());
        wosBasic.setSysUpdateTime(LocalDateTime.now());
        wosBasic.setBelongDate(belongDate);
        wosBasic.setDeptName(unitDept.getDept());
        wosBasic.setDeptId(deptId);
        wosBasic.setFilePath(path);
        wosBasic.setCTi(title);
        wosBasicMapper.updateById(wosBasic);

        return new ResultBean<>("操作成功");
    }

    //    //@ApiOperation(value = "07-WOS文献模块上传本地PDF文件覆盖全文链接")
    @GetMapping("upload_pdf_url_local")
//    @ApiImplicitParams({
//
//            @ApiImplicitParam(name = "id", value = "文章数据ID"), @ApiImplicitParam(name = "path", value = "先调用上传接口 上传接口返回文件路径后当做参数带回到这里"),})
    public ResultBean<Object> upload_pdf_url_local(Integer id, String path) {
        WosBasic wosBasic = wosBasicMapper.selectById(id);
        wosBasic.setFileType(2);//更改为本地上传的文件链接
        wosBasic.setFilePath(path);
        wosBasicMapper.updateById(wosBasic);
        return new ResultBean<>("操作成功");
    }

    //    //@ApiOperation(value = "09-单位下文章的下拉菜单")
//    @GetMapping("unit_article_year")
//
//    public ResultBean<Object> unit_article_year() {
//        System.out.println("当前登录人" + userUtil.getUid());
//        SysUser one = new LambdaQueryChainWrapper<>(sysUserMapper).eq(SysUser::getId, userUtil.getUid()).one();
//        List<WosBasic> list = new LambdaQueryChainWrapper<>(wosBasicMapper).select(WosBasic::getCPy, WosBasic::getGid, WosBasic::getSoType)
//                .eq(WosBasic::getSoType, 1).eq(WosBasic::getGid, one.getGid()).ne(WosBasic::getCPy, "").isNotNull(WosBasic::getCPy).list();
//        Map<String, Long> map = list.stream().collect(Collectors.groupingBy(WosBasic::getCPy, Collectors.counting()));
//        return new ResultBean<>(paseMap(map));
//    }

    //    //@ApiOperation(value = "10-新增单篇文章的跟踪记录")
    @GetMapping("unit_article_extend")
//    @ApiImplicitParams({@ApiImplicitParam(name = "wosId", value = "单位ID,就是单位表的id"), @ApiImplicitParam(name = "type", value = "跟踪记录,这几个都是文本框带时间  1备注 2文字剖析 3图片剖析 4学术不端"), @ApiImplicitParam(name = "content", value = "记录文本"),})
    public ResultBean<Object> unit_article_extend(WosExtend wosExtend) {
        if (wosExtend.getWosId() == null) {
            return new ResultBean<>("操作失败");
        }
        wosExtendMapper.insert(wosExtend);
        return new ResultBean<>("操作成功");
    }

    //    //@ApiOperation(value = "10-新增单篇文章的跟踪记录")
    @GetMapping("unit_article_extend_update")
//    @ApiImplicitParams({@ApiImplicitParam(name = "wosId", value = "单位ID,就是单位表的id"), @ApiImplicitParam(name = "type", value = "跟踪记录,这几个都是文本框带时间  1备注 2文字剖析 3图片剖析 4学术不端"), @ApiImplicitParam(name = "content", value = "记录文本"),})
    public ResultBean<Object> unit_article_extend_update(WosExtend wosExtend) {
        if (wosExtend.getWosId() == null) {
            return new ResultBean<>("操作失败");
        }
        wosExtendMapper.updateById(wosExtend);
        return new ResultBean<>("操作成功");
    }

    //    //@ApiOperation(value = "10-新增单篇文章的跟踪记录")
    @GetMapping("unit_article_extend_delete")
//    @ApiImplicitParams({@ApiImplicitParam(name = "wosId", value = "单位ID,就是单位表的id"), @ApiImplicitParam(name = "type", value = "跟踪记录,这几个都是文本框带时间  1备注 2文字剖析 3图片剖析 4学术不端"), @ApiImplicitParam(name = "content", value = "记录文本"),})
    public ResultBean<Object> unit_article_extend_delete(Integer id) {
        wosExtendMapper.deleteById(id);
        return new ResultBean<>("操作成功");
    }



    //    //@ApiOperation(value = "上传中文数据")
    @GetMapping("del_wos")
    public ResultBean<Object> del_wos(Integer id) {
        WosBasic wosBasic = wosBasicMapper.selectById(id);
        wosBasic.setDelFlag(1);
        wosBasicMapper.updateById(wosBasic);
        return new ResultBean<>("操作成功");
    }

    //    //@ApiOperation(value = "11-查看单个文章的单个类型的跟踪记录")
    @GetMapping("unit_article_record")
//    @ApiImplicitParams({@ApiImplicitParam(name = "wosId", value = "单位ID,就是单位表的id"), @ApiImplicitParam(name = "type", value = "跟踪记录,这几个都是文本框带时间  1备注 2文字剖析 3图片剖析 4学术不端"),
//
//    })
    public ResultBean<Object> unit_article_record(Integer wosId, Integer type) {
        List<WosExtend> list = new LambdaQueryChainWrapper<>(wosExtendMapper).eq(WosExtend::getWosId, wosId).eq(WosExtend::getType, type).orderByAsc(WosExtend::getId).list();
        return new ResultBean<>(list);
    }

    //    //@ApiOperation(value = "12-查看全文连接")
    @GetMapping("unit_article_pdf")
//    @ApiImplicitParams({@ApiImplicitParam(name = "wosId", value = "单位ID,就是单位表的id"),})
    public ResultBean<Object> unit_article_pdf(Integer wosId) {
        WosBasic wosBasic = wosBasicMapper.selectById(wosId);
        String pdfUrl = wosBasic.getPdfUrl();
        String getpdfurl = PdfUtil.getpdfurl(pdfUrl, 1, 1);
        return new ResultBean<>(getpdfurl);
    }

    @GetMapping("unit_article")
    public ResultBean<Object> unit_article(Integer soType, Integer page, Integer limit, Integer alaFlag, String
            picCount,
                                           Integer netIsShow, Integer isShow,
                                           String unitName, String fundName,
                                           Integer deptId,
                                           Integer year,
                                           Integer type, String param, Integer copyFlag,
                                           Integer localType, Integer exclude) {
        if (page == null) {
            page = 1;
        }
        if (limit == null) {
            limit = 10;
        }
        LambdaQueryChainWrapper<WosBasic> queryChainWrapper = new LambdaQueryChainWrapper<>(wosBasicMapper);
        queryChainWrapper.select(WosBasic::getId, WosBasic::getGid, WosBasic::getDeptName, WosBasic::getCTi, WosBasic::getCUt, WosBasic::getCPm, WosBasic::getIsShow, WosBasic::getJsonFlag, WosBasic::getNetIsShow, WosBasic::getNetJsonFlag, WosBasic::getCopyFlag, WosBasic::getSysUpdateTime, WosBasic::getFilePath, WosBasic::getFileType, WosBasic::getPdfUrl, WosBasic::getAuFlag, WosBasic::getAuMsgFlag, WosBasic::getAnalysisFlag, WosBasic::getTxtAnaFlag, WosBasic::getAnalysisMap, WosBasic::getPicCount, WosBasic::getAuthor, WosBasic::getBelongDate, WosBasic::getReFiD, WosBasic::getUploadName,
                //20230908 新增委托人部分
                WosBasic::getDeptEntrust, WosBasic::getDeptEntrustCheckTime, WosBasic::getDeptEntrustFinishFlag, WosBasic::getBidId,
                //新增返回文字相似度处理
                WosBasic::getTxtSame,
                //20230913 新增图片/文字/图文区分
                WosBasic::getSplit, WosBasic::getSplitType, WosBasic::getAdmCheck, WosBasic::getSoType, WosBasic::getAnnex, WosBasic::getMasterId, WosBasic::getMaster, WosBasic::getResultWord,
                //新增时间相关
                WosBasic::getSysCreateTime, WosBasic::getSysUpdateTime, WosBasic::getUid, WosBasic::getClientPicPath, WosBasic::getClientTxtPath, WosBasic::getClientUuid, WosBasic::getClientPhone, WosBasic::getClientRealName
                //20240519 增加删除
                , WosBasic::getDelFlag
        );
        //如果当前用户不是管理员,则只查看自己的
        int loginIdAsInt = userUtil.getUid();
        System.out.println("当前登录人__" + loginIdAsInt);

        queryChainWrapper.ne(WosBasic::getDelFlag, 1);

        //用来区分wos数据和单位本地文献数据
        if (soType != null) {
            queryChainWrapper.eq(WosBasic::getSoType, soType);
        }
        //如果登陆者为一级管理员,则只能看到自己被上传到自己名下的文章

        //只能看到对应单位下的文章

        //是否已分析
        if (alaFlag != null) {
            queryChainWrapper.and(i -> i.eq(WosBasic::getAnalysisFlag, alaFlag).or().eq(WosBasic::getTxtAnaFlag, alaFlag));
        }
        //图片数量过滤
        if (!StringUtil.isEmpty(picCount)) {
            String[] split = picCount.split("###");
            queryChainWrapper.ge(WosBasic::getPicCount, split[0]);
            queryChainWrapper.le(WosBasic::getPicCount, split[1]);
            queryChainWrapper.ne(WosBasic::getPicCount, 0);
            queryChainWrapper.isNotNull(WosBasic::getPicCount);
        }
        //是否有连线图
        if (isShow != null && isShow == 1) {
            queryChainWrapper.eq(WosBasic::getIsShow, isShow);
        }
        //是否有全网对比连线图
        if (netIsShow != null && netIsShow == 1) {
            queryChainWrapper.eq(WosBasic::getNetIsShow, netIsShow);
        }
        //科室
        if (deptId != null) {
            queryChainWrapper.eq(WosBasic::getDeptId, deptId);
        }


        //是否学术不端
        if (copyFlag != null) {
            queryChainWrapper.eq(WosBasic::getCopyFlag, copyFlag);
        }
        //是否有pmid/ut号检索
        if (!StringUtil.isEmpty(param)) {
            param = param.trim();
            if (param.startsWith("WOS") || param.length() > 10) {
                queryChainWrapper.like(WosBasic::getCUt, param);
                System.out.println("通过UT_" + param);
            } else {
                queryChainWrapper.eq(WosBasic::getCPm, param);
            }
        }
        //作者类型
        if (exclude == null) {
            if (type != null) {
                if (type == 1) {//只要第一作者
                    queryChainWrapper.eq(WosBasic::getCoFlag, 1);
                }
                if (type == 2) {//只要通讯作者
                    queryChainWrapper.eq(WosBasic::getRpFlag, 1);
                }
                if (type == 3) {//第一作者和通讯作者
                    queryChainWrapper.eq(WosBasic::getCoFlag, 1);
                    queryChainWrapper.eq(WosBasic::getRpFlag, 1);
                }
                if (type == 4) {//第一作者或通讯作者
                    queryChainWrapper.and(i -> {
                        i.eq(WosBasic::getCoFlag, 1).or().eq(WosBasic::getRpFlag, 1);
                    });
                }
            }
        } else {
            if (type != null) {
                if (type == 1) {//只要第一作者
                    queryChainWrapper.eq(WosBasic::getExcludeCo, 1);
                } else if (type == 2) {//只要通讯作者
                    queryChainWrapper.eq(WosBasic::getRpFlag, 1);
                } else if (type == 3) {//第一作者和通讯作者
                    queryChainWrapper.eq(WosBasic::getExcludeCoAndRp, 1);
                } else if (type == 4) {//第一作者或通讯作者
                    queryChainWrapper.eq(WosBasic::getExcludeCoOrRp, 1);
                } else {
                    queryChainWrapper.eq(WosBasic::getExcludeAll, 1);
                }
            }
        }

        //queryChainWrapper.orderByDesc(WosBasic::getId);

        //首先看未受理
        // queryChainWrapper.orderByAsc(WosBasic::getAnalysisFlag);
        queryChainWrapper.orderByDesc(WosBasic::getId);
        //基金名字
        if (!StringUtil.isEmpty(fundName)) {
            queryChainWrapper.last(" and  JSON_CONTAINS( stand_fund , JSON_ARRAY('" + fundName + "'))");
        }
        //单位名字
        if (!StringUtil.isEmpty(unitName)) {
            queryChainWrapper.last(" and  JSON_CONTAINS( stand_unit_rp_sp , JSON_ARRAY('" + unitName + "'))");

        }
        //三项类型 图片/文字/图文
        if (localType != null) {
            queryChainWrapper.eq(WosBasic::getSplitType, localType);
        }
        if (year != null) {
            queryChainWrapper.eq(WosBasic::getCPy, year);
        }
        //这里是真正结果
        Page<WosBasic> basicPage = queryChainWrapper.page(new Page<>(page, limit));
        List<WosBasic> records = basicPage.getRecords();

        RuijinSameConfig ruijinSameConfigs = ruijinSameConfigMapper.selectOne(new QueryWrapper<RuijinSameConfig>().eq("na", "文字查重率预警提示"));

        log.info("ruijinSameConfigs" + ruijinSameConfigs);

        for (WosBasic wosBasic : records) {

            Integer wosBasicId = wosBasic.getId();

            if (StringUtil.isNotNull(wosBasic.getTxtSame()) && StringUtil.isNotNull(ruijinSameConfigs)) {
                // 1 代表没有超过 2 代表超过
                if (wosBasic.getTxtSame() >= Double.valueOf(ruijinSameConfigs.getVal().replace("%", ""))) {
                    wosBasic.setTxtSameFlag(2);
                } else {
                    wosBasic.setTxtSameFlag(1);
                }
            } else {
                wosBasic.setTxtSameFlag(1);
            }


            //去掉下划线
            if (wosBasic.getCTi().contains("___")) {
                wosBasic.setCTi(wosBasic.getCTi().split("___")[1]);
            }
            //如果用户查看的是图文

            try {
                PaperAna paperAna = new LambdaQueryChainWrapper<>(anaMapper).eq(PaperAna::getWosId, wosBasic.getId()).one();
                if (paperAna != null) {
                    String resultWord = paperAna.getResultWord();
                    resultWord = resultWord.replace(resultPath, "");
                    paperAna.setResultWord(resultWord);

                    String resultPdf = paperAna.getResultPdf();
                    //现在版本把pdf 的文字去掉了 节省空间 后续用到再打开
                    if (StringUtil.isNotNull(resultPdf)) {
                        resultPdf = resultPdf.replace(resultPath, "");
                        paperAna.setResultPdf(resultPdf);
                    }
                    wosBasic.setPaperAna(paperAna);
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("获取图文结果报错");
            }
            try {
                if (StringUtil.isNotNull(wosBasic.getResultWord())) {
                    String replace = wosBasic.getResultWord().replace(resultPath, "");
                    wosBasic.setResultWord(replace);
                }
            } catch (Exception E2) {
                System.out.println("纯文字获取");
            }


            String analysisMap = wosBasic.getAnalysisMap();
            try {
//                if (!StringUtil.isEmpty(analysisMap) && analysisMap.length() > 2) {
//                    Map<Integer, Integer> map = JSONObject.parseObject(analysisMap, Map.class);
//                    if (map.containsKey(loginIdAsInt)) {
//                        FileRecord fileRecord = fileRecordsService.getBaseMapper().selectById(map.get(loginIdAsInt));
//                        if (fileRecord != null) {
//                            wosBasic.setAnalysisFlag(1);
//                        }
//                    }
//                }
                if (!StringUtil.isEmpty(analysisMap) && analysisMap.length() > 2) {
                    wosBasic.setAnalysisFlag(1);
                }
            } catch (Exception e) {
                log.error("判断是否有分析记录报错");
            }

        }
        return new ResultBean<>(basicPage);
    }



    //    //@ApiOperation(value = "12-2-查看本地文件")
    @GetMapping("unit_article_file")
//    @ApiImplicitParams({@ApiImplicitParam(name = "wosId", value = "单位ID,就是单位表的id"),})
    public ResultBean<Object> unit_article_file(Integer wosId) {
        WosBasic wosBasic = wosBasicMapper.selectById(wosId);
        return new ResultBean<>(wosBasic.getFilePath());
    }

    //    //@ApiOperation(value = "13-修改文章学术不端状态")
//    @GetMapping("unit_article_copy")
////    @ApiImplicitParams({@ApiImplicitParam(name = "wosId", value = "单位ID,就是单位表的id"), @ApiImplicitParam(name = "type", value = "0待定 1是 2否"),})
//    @OperationLog(operationModule = "修改文章学术不端状态", operationType = "UPDATE", operationDesc = "修改文章学术不端状态")
//    public ResultBean<Object> unit_article_copy(Integer wosId, Integer type) {
//        WosBasic wosBasic = wosBasicMapper.selectById(wosId);
//        wosBasic.setCopyFlag(type);
//        wosBasic.setSysUpdateTime(LocalDateTime.now());
//        wosBasicMapper.updateById(wosBasic);
//
//        int loginIdAsInt = userUtil.getUid();
//        SysUser sysUser = sysUserMapper.selectById(loginIdAsInt);
//        sysUser.setConfirmCount(sysUser.getConfirmCount() + 1);
//        sysUserMapper.updateById(sysUser);
//
//        return new ResultBean<>("操作成功");
//    }

    //    //@ApiOperation(value = "14-论文剖析-单篇文章-异步")
    @GetMapping("check_pdf_async")
//    @ApiImplicitParams({@ApiImplicitParam(name = "wosId", value = "每一篇文件的ID"), @ApiImplicitParam(name = "reload", value = "是否覆盖之前的文件 0 否 1是"), @ApiImplicitParam(name = "userId", value = "管理员审核成功之后从订单中获取uid"),})
    @SneakyThrows
    @OperationLog(operationModule = "论文剖析-单篇文章-异步", operationType = "UPDATE", operationDesc = "点击论文剖析")
    public ResultBean<Object> check_pdf_async(Integer wosId) {


        Integer uid = userUtil.getUid();

        System.out.println("当前访问的UID是___" + uid);
        /**
         * 做记录
         */
        Long count = new LambdaQueryChainWrapper<>(sysQueenMapper).eq(SysQueen::getUid, uid).eq(SysQueen::getStatus, 0).eq(SysQueen::getType, 1).count();
        if (count >= 10) {
            return new ResultBean<>(3, "当前系统任务过多,请稍后重试");
        }

        SysQueen sysQueen = new SysQueen();
        sysQueen.setUid(uid);
        sysQueen.setType(1);
        sysQueen.setStatus(0);
        sysQueen.setWosId(wosId);
        sysQueen.setSysCreateTime(LocalDateTime.now());
        sysQueen.setSysUpdateTime(LocalDateTime.now());
        sysQueenMapper.insert(sysQueen);


        WosBasic wosBasic = wosBasicMapper.selectById(wosId);
        //首先标记分析中的状态
        wosBasic.setAnalysisFlag(-1);
        wosBasic.setAnalysisMap("");
        wosBasic.setAnalysisTime(System.currentTimeMillis());
        wosBasicMapper.updateById(wosBasic);

        return new ResultBean<>("操作成功,一键分析结果需3-10分钟,请于稍后刷新当前页面,全网检索结果将于24H之内计算完毕");
    }

    //    //@ApiOperation(value = "15-点击论文剖析的查看按钮,返回需要跳转的网址id")
    @GetMapping("check_pdf_id")
//    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "WOS文章的ID"),
//
//    })
    @OperationLog(operationModule = "点击查看", operationType = "SELECT", operationDesc = "点击查看分析结果")
    public ResultBean<Object> check_pdf_id(Integer id) {
        WosBasic wosBasic = wosBasicMapper.selectById(id);
        String analysisMap = wosBasic.getAnalysisMap();
        int loginIdAsInt = userUtil.getUid();
        if (!StringUtil.isEmpty(analysisMap) && analysisMap.length() > 2) {
            List<SysQueen> list = new LambdaQueryChainWrapper<>(sysQueenMapper)
                    .eq(SysQueen::getWosId, id)
                    .eq(SysQueen::getUid, userUtil.getUid())
                    .eq(SysQueen::getStatus, 1)
                    .eq(SysQueen::getCheckFlag, 0).list();
            if (list.size() > 0) {
                for (SysQueen sysQueen : list) {
                    sysQueen.setCheckFlag(1);
                    sysQueenMapper.updateById(sysQueen);
                }
            }
            Map<Integer, Integer> map = JSONObject.parseObject(analysisMap, Map.class);
            Integer integer = map.get(1);
            if (integer != null) {
                return new ResultBean<>(integer);
            }
        }
        return new ResultBean<>(null);
    }

    //    //@ApiOperation(value = "15-点击论文剖析的查看按钮,返回需要跳转的网址id")
    @GetMapping("check_pdf_id_ignore")
//    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "WOS文章的ID"),
//
//    })
    public ResultBean<Object> check_pdf_id_ignore(Integer id) {
        SysQueen sysQueen = sysQueenMapper.selectById(id);
        sysQueen.setCheckFlag(1);
        sysQueenMapper.updateById(sysQueen);
        return new ResultBean<>("操作成功");
    }

    //@ApiOperation(value = "16-批量分析")?
    @GetMapping("check_pdf_ids")
    public ResultBean<Object> check_pdf_ids(String ids) throws IOException {
        String[] split = ids.split("AAAAA");

        int uid = userUtil.getUid();
        Long count = new LambdaQueryChainWrapper<>(sysQueenMapper).eq(SysQueen::getUid, uid).eq(SysQueen::getStatus, 0).eq(SysQueen::getType, 1).count();
        if (count >= 10) {
            return new ResultBean<>(3, "当前系统任务过多,请稍后重试");
        }
        if (count + split.length >= 10) {
            return new ResultBean<>(3, "当前系统任务过多,请稍后重试");
        }

        for (String idOne : split) {
            try {
                log.info("准备进行异步的一键分析");
                WosBasic wosBasic = wosBasicMapper.selectById(idOne);
                if (wosBasic.getAnalysisFlag() != -1) {
                    check_pdf_async(Integer.parseInt(idOne));
                }
            } catch (Exception e) {
                log.error("一键分析中单篇文章分析报错");
            }
        }
        return new ResultBean<>("操作成功,预计分析时间2~4H");
    }

    //    //@ApiOperation(value = "17-查看一键分析结果")
    @GetMapping("check_pdf_result")
    public ResultBean<Object> check_pdf_result(Integer wosId) {
        WosBasic wosBasic = wosBasicMapper.selectById(wosId);
        return new ResultBean<>(wosBasic);
    }

    //@ApiOperation(value = "18-查看第一作者和通讯作者")
    @GetMapping("check_co_rp")
//    @ApiImplicitParams({@ApiImplicitParam(name = "wosId", value = "每一篇文件的ID"),})
    public Object check_co_rp(Integer wosId) {
        AuthorMess authorMess = new AuthorMess();
        List<String> markList = new ArrayList<>();

        WosBasic wosBasic = wosBasicMapper.selectById(wosId);
        wosBasic.setAuMsgFlag(1);
        wosBasicMapper.updateById(wosBasic);

        UnitBasic unitBasic = unitBasicMapper.selectById(wosBasic.getGid());

        String mark = unitBasic.getMark();
        authorMess.setMarkStr(mark);
        if (!StringUtil.isEmpty(mark)) {
            String[] split = mark.split("###");
            for (String markOne : split) {
                markList.add(markOne);
            }
        }

        /**
         * 设置第一作者_原始
         */
        List<CoAuthor> coList = new ArrayList<>();
        String cc1 = wosBasic.getCC1();
        cc1 = CheckFirstUnit.reArgs(cc1);
        String c1 = getC1(cc1);//获取原始 C1
        CoAuthor coAndRp = new CoAuthor();
        coAndRp.setEnName(c1);//这里又要把作者名字加上
        coAndRp.setCnName(StringUtil.isEmpty(c1) ? "" : YouDaoTransLate.DoEnToCnTrans(c1).replace("2 .", "").trim());
        coList.add(coAndRp);
        authorMess.setCoAuthor(coList);

        /**
         * 设置通讯作者_原始
         */
        List<RpAuthor> rpList = new ArrayList<>();
        String cRp = wosBasic.getCRp();
        cRp = CheckFirstUnit.reArgs(cRp);
        if (null != cRp && cRp.length() > 5) {
            cRp = cRp.replace(" (通讯作者)，", " (corresponding author), ");
            cRp = cRp.indexOf(" (corresponding author), ") > 0 ? cRp.substring(cRp.indexOf(" (corresponding author), ")) : cRp;
            if (cRp.contains(" (corresponding author), ")) {
                String[] split = cRp.split(" \\(corresponding author\\), ");
                for (String t : split) {
                    String told = t;
                    t = t.indexOf("; ") > 0 ? t.substring(0, t.indexOf("; ")) : t;
                    if (t.length() > 5) {
                        RpAuthor rpAuthor = new RpAuthor();
                        rpAuthor.setEnName(t);//原先是 T
                        String s1 = YouDaoTransLate.DoEnToCnTrans(t);
                        if (s1.startsWith("2 .")) {
                            s1 = s1.replace("2 .", "");
                        }
                        rpAuthor.setCnName(s1.trim());
                        rpList.add(rpAuthor);
                    }
                }
            }
        }
        authorMess.setRpAuthor(rpList);
        /**
         * 设置基金信息_原始
         */
        List<RpAuthor> fuList = new ArrayList<>();
        String cFu = wosBasic.getCFu();
        String[] fuArry = cFu.split("; ");
        for (String fuOne : fuArry) {
            fuOne = (fuOne.indexOf("[") > 0) ? fuOne.substring(0, fuOne.indexOf("[")).trim() : fuOne;
            RpAuthor fuAuthor = new RpAuthor();
            fuAuthor.setEnName(fuOne);
            fuAuthor.setCnName(YouDaoTransLate.DoEnToCnTrans(fuOne));
            fuList.add(fuAuthor);
        }
        authorMess.setFuAuthor(fuList);
        /**
         * 标准基金名字_规范
         */
        List<RpAuthor> standFundList = new ArrayList<>();
        String standFund = wosBasic.getStandFund();
        if (!StringUtil.isEmpty(standFund)) {
            List<String> fundStandList = JSONObject.parseArray(standFund, String.class);
            for (String one : fundStandList) {
                RpAuthor fundStand = new RpAuthor();
                fundStand.setCnName(one);
                standFundList.add(fundStand);
            }
        }
        authorMess.setFundStand(standFundList);


        /**
         * 标准单位名字_第一作者_规范
         */
        List<RpAuthor> standCoList = new ArrayList<>();
        String standUnitCo = wosBasic.getStandUnitCo();
        if (!StringUtil.isEmpty(standUnitCo)) {
            RpAuthor coStand = new RpAuthor();
            coStand.setCnName(standUnitCo);
            standCoList.add(coStand);
        }
        authorMess.setCoStand(standCoList);
        /**
         * 标准单位名字_通讯作者_规范
         */
        List<RpAuthor> standRpList = new ArrayList<>();
        String standRp = wosBasic.getStandUnitRp();
        if (!StringUtil.isEmpty(standRp)) {
            List<String> rpStandList = JSONObject.parseArray(standRp, String.class);
            for (String one : rpStandList) {
                RpAuthor fundStand = new RpAuthor();
                fundStand.setCnName(one);
                standRpList.add(fundStand);
            }
        }
        authorMess.setRpStand(standRpList);


        markList.add("ZFL5756");
        /**
         * 第一作者_原始
         */
        List<CoAuthor> coAuthor = authorMess.getCoAuthor();
        for (CoAuthor author : coAuthor) {

            String cnName = author.getCnName();
            String cnNameOld = cnName;
            cnName = cnName.toUpperCase();
            String enName = author.getEnName();
            String enNameOld = enName;
            enName = enName.toUpperCase();
            for (String markOne : markList) {//univ 大学
                StringBuffer finalStr = new StringBuffer();
                markOne = markOne.toUpperCase();
                if (cnName.contains(markOne)) {
                    String one = cnNameOld.substring(cnName.indexOf(markOne), cnName.indexOf(markOne) + markOne.length());
                    cnNameOld = cnNameOld.replace(one, "<span>" + one + "</span>");
                    cnName = cnNameOld.toUpperCase();
                }
                if (enName.contains(markOne)) {
                    String one = enNameOld.substring(enName.indexOf(markOne), enName.indexOf(markOne) + markOne.length());
                    enNameOld = enNameOld.replace(one, "<span>" + one + "</span>");
                    enName = enNameOld.toUpperCase();
                }
            }
            author.setCnName(cnNameOld);
            author.setEnName(enNameOld);
        }


        /**
         * 通讯作者_原始
         */
        List<RpAuthor> rpAuthor = authorMess.getRpAuthor();
        for (RpAuthor author : rpAuthor) {

            String cnName = author.getCnName();
            String cnNameOld = cnName;
            cnName = cnName.toUpperCase();
            String enName = author.getEnName();
            String enNameOld = enName;
            enName = enName.toUpperCase();
            for (String markOne : markList) {//univ 大学
                StringBuffer finalStr = new StringBuffer();

                markOne = markOne.toUpperCase();
                if (cnName.contains(markOne)) {
                    String one = cnNameOld.substring(cnName.indexOf(markOne), cnName.indexOf(markOne) + markOne.length());
                    cnNameOld = cnNameOld.replace(one, "<span>" + one + "</span>");
                    cnName = cnNameOld.toUpperCase();
                }
                if (enName.contains(markOne)) {
                    String one = enNameOld.substring(enName.indexOf(markOne), enName.indexOf(markOne) + markOne.length());
                    enNameOld = enNameOld.replace(one, "<span>" + one + "</span>");
                    enName = enNameOld.toUpperCase();
                }

            }
            author.setCnName(cnNameOld);
            author.setEnName(enNameOld);
        }
        /**
         * 基金信息 原始
         */
        List<RpAuthor> fuAuthor = authorMess.getFuAuthor();
        for (RpAuthor author : fuAuthor) {

            String cnName = author.getCnName();
            String cnNameOld = cnName;
            cnName = cnName.toUpperCase();
            String enName = author.getEnName();
            String enNameOld = enName;
            enName = enName.toUpperCase();
            for (String markOne : markList) {//univ 大学
                StringBuffer finalStr = new StringBuffer();

                markOne = markOne.toUpperCase();
                if (cnName.contains(markOne)) {
                    String one = cnNameOld.substring(cnName.indexOf(markOne), cnName.indexOf(markOne) + markOne.length());
                    cnNameOld = cnNameOld.replace(one, "<span>" + one + "</span>");
                    cnName = cnNameOld.toUpperCase();
                }
                if (enName.contains(markOne)) {
                    String one = enNameOld.substring(enName.indexOf(markOne), enName.indexOf(markOne) + markOne.length());
                    enNameOld = enNameOld.replace(one, "<span>" + one + "</span>");
                    enName = enNameOld.toUpperCase();
                }

            }
            author.setCnName(cnNameOld);
            author.setEnName(enNameOld);
        }
        /**
         * 标准基金_规范
         */
        List<RpAuthor> authorMessFundStand = authorMess.getFundStand();
        if (authorMessFundStand.size() > 0) {
            for (RpAuthor author : authorMessFundStand) {
                String cnName = author.getCnName();
                String cnNameOld = cnName;
                cnName = cnName.toUpperCase();
                for (String markOne : markList) {//univ 大学
                    StringBuffer finalStr = new StringBuffer();
                    markOne = markOne.toUpperCase();
                    if (cnName.contains(markOne)) {
                        String one = cnNameOld.substring(cnName.indexOf(markOne), cnName.indexOf(markOne) + markOne.length());
                        cnNameOld = cnNameOld.replace(one, "<span>" + one + "</span>");
                        cnName = cnNameOld.toUpperCase();
                    }
                }
                author.setCnName(cnNameOld);
            }
        }

        /**
         * 标准名称 第一作者 规范
         */
        List<RpAuthor> authorMessCoStand = authorMess.getCoStand();
        if (authorMessCoStand.size() > 0) {
            for (RpAuthor author : authorMessCoStand) {
                String cnName = author.getCnName();
                String cnNameOld = cnName;
                cnName = cnName.toUpperCase();
                for (String markOne : markList) {//univ 大学
                    StringBuffer finalStr = new StringBuffer();
                    markOne = markOne.toUpperCase();
                    if (cnName.contains(markOne)) {
                        String one = cnNameOld.substring(cnName.indexOf(markOne), cnName.indexOf(markOne) + markOne.length());
                        cnNameOld = cnNameOld.replace(one, "<span>" + one + "</span>");
                        cnName = cnNameOld.toUpperCase();
                    }
                }
                author.setCnName(cnNameOld);
            }
        }

        /**
         * 标准名称 通讯作者 规范
         */
        List<RpAuthor> authorMessRpStand = authorMess.getRpStand();
        if (authorMessRpStand.size() > 0) {
            for (RpAuthor author : authorMessRpStand) {
                String cnName = author.getCnName();
                String cnNameOld = cnName;
                cnName = cnName.toUpperCase();
                for (String markOne : markList) {//univ 大学
                    StringBuffer finalStr = new StringBuffer();
                    markOne = markOne.toUpperCase();
                    if (cnName.contains(markOne)) {
                        String one = cnNameOld.substring(cnName.indexOf(markOne), cnName.indexOf(markOne) + markOne.length());
                        cnNameOld = cnNameOld.replace(one, "<span>" + one + "</span>");
                        cnName = cnNameOld.toUpperCase();
                    }
                }
                author.setCnName(cnNameOld);
            }
        }

        return new ResultBean<>(authorMess);
    }

//    //@ApiOperation(value = "temp")
//    @GetMapping("chegao")
//    public void chegao(Integer wosId) {
//        List<WosBasic> wosBasics = wosBasicMapper.selectList(null);
//        for (WosBasic wosBasic : wosBasics) {
//            try {
//                if (StringUtil.isNotNull(wosBasic.getCPm())) {
//                    if (wosBasic.getCPm().length() > 3) {
//                        if (initController.pmidSet.contains(wosBasic.getCPm())) {
//                            wosBasic.setWithdrawFlag(1);
//                        }
//                    }
//                }
//                String s = wosBasic.getCTi().toLowerCase().trim();
//                if (s.startsWith("retraction") || s.startsWith("retracted") || s.startsWith("撤稿声明") || s.startsWith("撤回内容")) {
//                    wosBasic.setWithdrawFlag(1);
//                }
//                wosBasicMapper.updateById(wosBasic);
//                System.out.println("更新了___" + wosBasic.getId());
//            } catch (Exception e) {
//
//            }
//        }
//    }

    //@ApiOperation(value = "19-设置作者信息识别标识符")
    @GetMapping("set_mark")
//    @ApiImplicitParams({@ApiImplicitParam(name = "unitId", value = "单位ID,就是单位表的id"), @ApiImplicitParam(name = "mark", value = "标识 A###B###C", dataTypeClass = String.class),})
    public ResultBean<Object> set_mark(Integer unitId, String mark) {
        UnitBasic unitBasic = unitBasicMapper.selectById(unitId);
        unitBasic.setMark(mark);
        unitBasicMapper.updateById(unitBasic);
        return new ResultBean<>("操作成功");
    }

    //@ApiOperation(value = "20-提交给总管理员处理图片/图文")
    @GetMapping("adm_check")
    public ResultBean<Object> adm_check(Integer wosId) {
        WosBasic wosBasic = wosBasicMapper.selectById(wosId);
        wosBasic.setAdmCheck(1);
        wosBasicMapper.updateById(wosBasic);
        return new ResultBean<>("操作成功");
    }

    //@ApiOperation(value = "20-提交给总管理员处理_文字")
    @GetMapping("adm_check_con")
    public ResultBean<Object> adm_check_con(Integer wosId) {
        PaperAna paperAna = anaMapper.selectById(wosId);
        paperAna.setAdmCheck(1);
        anaMapper.updateById(paperAna);
        return new ResultBean<>("操作成功");
    }

    @Async
    public Integer start(String filePath, String searchPlan, Integer gid) throws IOException {
        searchPlan = searchPlan.trim().toLowerCase();
        filePath = uploadPath + filePath;
        System.out.println("开始任务" + filePath);
        AtomicInteger count = new AtomicInteger();

        String string = FileUtil.readUtf8String(filePath);
        String[] line = string.split("\n");
        String finalSearchPlan = searchPlan;
        Arrays.stream(line).parallel().forEach(i -> {

            String[] split = i.split("\t");

            WosBasic wosBasic = parseTxt(split);
            // WosBasic one2 = new LambdaQueryChainWrapper<>(wosBasicMapper).eq(WosBasic::getCUt, wosBasic.getCUt()).one();
            // if (one2 == null) {
            wosBasic.setGid(gid);
            wosBasic.setUid(1);

            /**
             * 设置数据来源
             */
            wosBasic.setSoType(1);

            /**
             * 设置第一或者通讯作者 / 科室名称
             */
            checkConeOrRpOrFund(wosBasic, finalSearchPlan);
            /**
             * 设置排除项
             */
            checkC1RpExclude(wosBasic, finalSearchPlan);
            /**
             * 设置国自然基金
             */
            String fuName = wosBasic.getCFu();
            int isChina = ((fuName.toLowerCase().contains("natur") && fuName.toLowerCase().contains("nation") && fuName.toLowerCase().contains("china")) || fuName.contains("NSFC")) ? 1 : 0;
            wosBasic.setFuFlag(isChina);

            /**
             * 判断是否是撤稿
             */
            if (wosBasic.getCPm().length() > 3) {
                if (initController.pmidSet.contains(wosBasic.getCPm())) {
                    wosBasic.setWithdrawFlag(1);
                }
            }
            String s = wosBasic.getCTi().toLowerCase().trim();
            if (s.startsWith("retraction") || s.startsWith("retracted") || s.startsWith("撤稿声明") || s.startsWith("撤回内容")) {
                wosBasic.setWithdrawFlag(1);
            }

            /**
             * 设置标准单位信息 第一作者
             */
            String cc1 = wosBasic.getCC1();
            cc1 = CheckFirstUnit.reArgs(cc1);
            String c1 = getC1(cc1);
            String co = getRuleName(c1, initController.unitRuleFile);
            wosBasic.setStandUnitCo(co);
            if (co.contains("-")) {
                wosBasic.setStandUnitCoSp(co.split("-")[1]);
            } else {
                wosBasic.setStandUnitCoSp(co);
            }

            /**
             * 设置标准单位信息 通讯作者 和 去掉 - 的通讯作者单位信息
             */
            List<String> rpList = new ArrayList<>();
            List<String> rpListSp = new ArrayList<>();
            String cRp = wosBasic.getCRp();
            cRp = CheckFirstUnit.reArgs(cRp);
            if (null != cRp && cRp.length() > 5) {
                cRp = cRp.replace(" (通讯作者)，", " (corresponding author), ");
                cRp = cRp.indexOf(" (corresponding author), ") > 0 ? cRp.substring(cRp.indexOf(" (corresponding author), ")) : cRp;
                if (cRp.contains(" (corresponding author), ")) {
                    String[] splitRP = cRp.split(" \\(corresponding author\\), ");
                    for (String t : splitRP) {
                        t = t.indexOf("; ") > 0 ? t.substring(0, t.indexOf("; ")) : t;
                        if (t.length() > 5) {
                            String rp = getRuleName(t, initController.unitRuleFile);
                            rpList.add(rp);
                            if (rp.contains("-")) {
                                rpListSp.add(rp.split("-")[1]);
                            } else {
                                rpListSp.add(rp);
                            }
                        }
                    }
                }
            }
            wosBasic.setStandUnitRp(JSONObject.toJSONString(rpList));
            wosBasic.setStandUnitRpSp(JSONObject.toJSONString(rpListSp));
            /**
             * 设置标准基金信息
             */
            List<String> fuList = new ArrayList<>();
            String cFu = wosBasic.getCFu();
            String[] fuArry = cFu.split("; ");
            for (String fuOne : fuArry) {
                String ruleName = getRuleName(fuOne, initController.fundRuleFile);
                fuList.add(ruleName);
            }
            wosBasic.setStandFund(JSONObject.toJSONString(fuList));
            if (!"PY".equals(wosBasic.getCPy())) {
                int insert = wosBasicMapper.insert(wosBasic);
                count.getAndIncrement();
            }
            //   }
        });


        return count.get();
    }

    public List<KeyAndValue> paseMap(Map<String, Long> map) {
        List<KeyAndValue> list = new ArrayList<>();
        Set<Map.Entry<String, Long>> entries = map.entrySet();
        for (Map.Entry<String, Long> entry : entries) {
            KeyAndValue keyAndValue = new KeyAndValue();
            keyAndValue.setKeyObject(entry.getKey());
            keyAndValue.setValueObject((entry.getValue()));
            try {
                Integer.parseInt(entry.getKey());
                list.add(keyAndValue);
            } catch (Exception e) {
            }
        }
        list.sort(new Comparator<KeyAndValue>() {
            @Override
            public int compare(KeyAndValue o1, KeyAndValue o2) {
                return Integer.parseInt(o2.getKeyObject()) - Integer.parseInt(o1.getKeyObject());
            }
        });
        return list;
    }

    /**
     * 解析Txt的方法
     */
    public WosBasic parseTxt(String[] strings) {

        // System.out.println("下载到的内容为:" + Arrays.asList(strings));

        WosBasic wos = new WosBasic();

        wos.setCPt(strings[0]);
        wos.setCAu(strings[1]);
        wos.setCBa(strings[2]);
        wos.setCBe(strings[3]);

        wos.setCGp(strings[4]);
        wos.setCAf(strings[5]);
        wos.setCBf(strings[6]);
        wos.setCCa(strings[7]);
        wos.setCTi(strings[8]);
        wos.setCSo(strings[9]);
        wos.setCSe(strings[10]);

        wos.setCBs(strings[11]);
        wos.setCLa(strings[12]);
        wos.setCDt(strings[13]);
        wos.setCCt(strings[14]);
        wos.setCCy(strings[15]);

        wos.setCCl(strings[16]);
        wos.setCSp(strings[17]);
        wos.setCHo(strings[18]);
        wos.setCDe(strings[19]);
        wos.setCId(strings[20]);

        wos.setCAb(strings[21]);
        wos.setCC1(strings[22]);
        wos.setCC3(strings[23]);
        wos.setCRp(strings[24]);
        wos.setCEm(strings[25]);

        wos.setCRi(strings[26]);
        wos.setCOi(strings[27]);
        wos.setCFu(strings[28]);
        wos.setCFp(strings[29]);
        wos.setCFx(strings[30]);

        wos.setCCr(strings[31]);
        wos.setCNr(strings[32]);
        wos.setCTc(strings[33]);
        wos.setCZ9(strings[34]);
        wos.setCU1(strings[35]);

        wos.setCU2(strings[36]);
        wos.setCPu(strings[37]);
        wos.setCPi(strings[38]);
        wos.setCPa(strings[39]);
        wos.setCSn(strings[40]);

        wos.setCEi(strings[41]);
        wos.setCBn(strings[42]);
        wos.setCJ9(strings[43]);
        wos.setCJi(strings[44]);
        wos.setCPd(strings[45]);

        wos.setCPy(strings[46]);
        wos.setCVl(strings[47]);
        wos.setCIs(strings[48]);
        wos.setCPn(strings[49]);
        wos.setCSu(strings[50]);

        wos.setCSi(strings[51]);
        wos.setCMa(strings[52]);
        wos.setCBp(strings[53]);
        wos.setCEp(strings[54]);
        wos.setCAr(strings[55]);

        wos.setCDi(strings[56]);
        wos.setCDl(strings[57]);
        wos.setCD2(strings[58]);
        wos.setCEa(strings[59]);
        wos.setCPg(strings[60]);

        wos.setCWc(strings[61]);
        wos.setCWe(strings[62]);
        wos.setCSc(strings[63]);
        wos.setCGa(strings[64]);
        wos.setCPm(strings[65]);

        wos.setCOa(strings[66]);
        wos.setCHc(strings[67]);
        wos.setCHp(strings[68]);
        wos.setCDa(strings[69]);
        wos.setCUt(strings[70].trim());

        return wos;
    }

    /**
     * 判断是否是第一作者或者通讯作者或者国自然基金
     *
     * @param wosBasic
     * @param searchPlan
     */
    public void checkConeOrRpOrFund(WosBasic wosBasic, String searchPlan) {
        try {

            boolean coFlag = false;
            boolean rpFlag = false;
            boolean auFlag = false;
            boolean cyFlag = false;

            String cc1 = wosBasic.getCC1();
            List<String> coList = CheckFirstUnit.getC1(initController.infoAndRuleMap.get(wosBasic.getGid()), cc1);
            wosBasic.setCoList(JSONObject.toJSONString(coList));

            /**
             * 判断是否是第一作者 单独
             */
            String c1 = getC1(cc1);
            c1 = c1.trim().toLowerCase();
            coFlag = CheckFirstUnit.doCheck(c1, searchPlan);
            /**
             * 判断是否是通讯作者 单独
             */
            String crp = wosBasic.getCRp();
            List<String> rpList = CheckFirstUnit.getRP(initController.infoAndRuleMap.get(wosBasic.getGid()), crp);
            wosBasic.setRpList(JSONObject.toJSONString(rpList));

            crp = crp.trim().toLowerCase();
            String[] rps = crp.split("\\.; ");
            for (String rp : rps) {
                boolean contains = CheckFirstUnit.doCheck(rp, searchPlan);
                if (contains) {
                    rpFlag = true;
                    break;
                }
            }


            if (coFlag) {
                wosBasic.setCoFlag(1);
            } else {
                wosBasic.setCoFlag(0);
            }
            if (rpFlag) {
                wosBasic.setRpFlag(1);
            } else {
                wosBasic.setRpFlag(0);
            }
            if (coFlag || rpFlag) {
                wosBasic.setAuFlag(1);
            } else {
                wosBasic.setAuFlag(0);
            }
            // if (wosBasic.getCoFlag() == 1) {
            /**
             * 设置参与作者
             */
            if (wosBasic.getCoFlag() == 0) {
                List<String> strings = getCyList(cc1);
                wosBasic.setCyFlag(0);
                A:
                for (String string : strings) {
                    boolean contains = CheckFirstUnit.doCheck(string, searchPlan);
                    if (contains) {
                        wosBasic.setCyFlag(1);
                        break A;
                    }
                }
            } else {
                wosBasic.setCyFlag(0);
            }


            //  }
            /**
             * 如果在这个单位下
             */
            if (wosBasic.getAuFlag() == 1) {
                boolean nextFlag = true;
                if (rpList.size() > 0) {

                    for (String s : rpList) {
                        if (initController.deptNameMap.get(wosBasic.getGid()).containsKey(s)) {

                            Integer integer = initController.deptNameMap.get(wosBasic.getGid()).get(s);
                            wosBasic.setDeptId(integer);
                            wosBasic.setDeptName(s);

                            nextFlag = false;
                            break;
                        }
                    }
                }
                if (nextFlag) {
                    if (coList.size() > 0) {
                        for (String s : coList) {
                            if (initController.deptNameMap.get(wosBasic.getGid()).containsKey(s)) {
                                Integer integer = initController.deptNameMap.get(wosBasic.getGid()).get(s);
                                wosBasic.setDeptId(integer);
                                wosBasic.setDeptName(s);
                                break;
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("获取C1失败");
        }

    }

    //获取参与作者
    public List<String> getCyList(String c1) {

        List<String> result = new ArrayList<>();
        String[] split = c1.split("; \\[");
        for (int i = 1; i < split.length; i++) {
            String s = split[i];
            s = s.indexOf("] ") > 0 ? s.substring(s.indexOf("] ") + "] ".length()) : s;

            if (s.length() > 5) {
                String ciUnit = getRuleName(s, initController.unitRuleFile);
                if (StringUtil.isNotNull(ciUnit)) {
                    result.add(ciUnit);
                }
            }
        }
        return result;
    }

    //获取参与作者_原始数据
    public List<String> getCyYsList(String c1) {

        List<String> result = new ArrayList<>();
        String[] split = c1.split("; \\[");
        for (int i = 1; i < split.length; i++) {
            String s = split[i];
            s = s.indexOf("] ") > 0 ? s.substring(s.indexOf("] ") + "] ".length()) : s;

            if (s.length() > 5) {
                if (StringUtil.isNotNull(s)) {
                    result.add(s);
                }
            }
        }
        return result;
    }

    //获取通讯作者
    public List<String> getRpList(String cRp) {
        List<String> rpList = new ArrayList<>();
        if (null != cRp && cRp.length() > 5) {
            cRp = cRp.replace(" (通讯作者)，", " (corresponding author), ");
            cRp = cRp.indexOf(" (corresponding author), ") > 0 ? cRp.substring(cRp.indexOf(" (corresponding author), ")) : cRp;
            if (cRp.contains(" (corresponding author), ")) {
                String[] splitRP = cRp.split(" \\(corresponding author\\), ");
                for (String t : splitRP) {
                    t = t.indexOf("; ") > 0 ? t.substring(0, t.indexOf("; ")) : t;
                    if (t.length() > 5) {
                        String rp = getRuleName(t, initController.unitRuleFile);
                        if (StringUtil.isNotNull(rp)) {
                            rpList.add(rp);
                        }
                    }
                }
            }
        }
        return rpList;
    }

    //获取通讯作者_原始数据
    public List<String> getRpListYs(String cRp) {
        List<String> rpList = new ArrayList<>();
        if (null != cRp && cRp.length() > 5) {
            cRp = cRp.replace(" (通讯作者)，", " (corresponding author), ");
            cRp = cRp.indexOf(" (corresponding author), ") > 0 ? cRp.substring(cRp.indexOf(" (corresponding author), ")) : cRp;
            if (cRp.contains(" (corresponding author), ")) {
                String[] splitRP = cRp.split(" \\(corresponding author\\), ");
                for (String t : splitRP) {
                    t = t.indexOf("; ") > 0 ? t.substring(0, t.indexOf("; ")) : t;
                    if (StringUtil.isNotNull(t)) {
                        rpList.add(t);
                    }
                }
            }
        }
        return rpList;
    }

    public void checkC1RpExclude(WosBasic wosBasic, String searchPlan) {

        //默认全都不展示
        boolean allFlag = false;
        boolean c1Flag = false;
        boolean rpFlag = false;
        boolean c1AndRpFlag = false;
        boolean c1OrRpFlag = false;
        boolean cyFlag = false;

        //获取C1 数据
        String cc1 = wosBasic.getCC1();

        String c1 = getC1(cc1);
        c1 = c1.trim().toLowerCase();
        boolean coFlag = CheckFirstUnit.doCheck(c1, searchPlan);
        if (coFlag) {
            c1Flag = affiliated(c1);
        }

        /**
         * 判断是否是通讯作者 单独
         */
        String crp = wosBasic.getCRp();
        crp = crp.trim().toLowerCase();
        String[] rps = crp.split("\\.; ");
        A:
        for (String rp : rps) {
            boolean contains = CheckFirstUnit.doCheck(rp, searchPlan);
            if (contains) {
                rpFlag = affiliated(rp);
                if (rpFlag) {
                    break A;
                }
            }
        }

        // if (c1Flag) {
        /**
         * 判断是不是参与作者
         */
        if (c1Flag == false) {
            List<String> strings = getCyList(cc1);
            A:
            for (String string : strings) {
                boolean contains = CheckFirstUnit.doCheck(string, searchPlan);
                if (contains) {
                    cyFlag = affiliated(string);
                    if (cyFlag) {
                        break A;
                    }
                }
            }
        }


        // }

        if (c1Flag && rpFlag) {
            c1AndRpFlag = true;
        }
        if (c1Flag || rpFlag) {
            c1OrRpFlag = true;
        }

        /**
         * 设置排除项的五项
         */
        if (c1Flag) {
            wosBasic.setExcludeCo(1);
        } else {
            wosBasic.setExcludeCo(0);
        }
        if (rpFlag) {
            wosBasic.setExcludeRp(1);
        } else {
            wosBasic.setExcludeRp(0);
        }
        if (cyFlag) {
            wosBasic.setExcludeCy(1);
        } else {
            wosBasic.setExcludeCy(0);
        }
        if (wosBasic.getExcludeCo() == 1 || wosBasic.getExcludeRp() == 1 || wosBasic.getExcludeCy() == 1) {
            wosBasic.setExcludeAll(1);
        } else {
            wosBasic.setExcludeAll(0);
        }
        if (c1AndRpFlag) {
            wosBasic.setExcludeCoAndRp(1);
        } else {
            wosBasic.setExcludeCoAndRp(0);
        }
        if (c1OrRpFlag) {
            wosBasic.setExcludeCoOrRp(1);
        } else {
            wosBasic.setExcludeCoOrRp(0);
        }


    }


}
